package org.vectrics.recruiter.struts.tag;

import java.util.Collection;
import java.util.Iterator;
import java.util.TreeSet;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.ecs.html.Input;
import org.apache.log4j.Category;
import org.vectrics.SystemException;
import org.vectrics.common.html.BorderTable;
import org.vectrics.common.html.Cell;
import org.vectrics.common.html.Row;
import org.vectrics.common.html.Table;
import org.vectrics.common.html.TextHelper;
import org.vectrics.domain.Domain;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.VectricsTagSupport;
import org.vectrics.user.Person;
import org.vectrics.user.PersonPrivilegeGroup;
import org.vectrics.user.PersonPrivilegeGroupType;
import org.vectrics.user.web.struts.UserGroupHelper;

/**
 *  Description of the Class
 *
 *@author     mmoore
 */
public class UserGroupSelectTag extends VectricsTagSupport {

	public static final long serialVersionUID = 361255369300234945L;
    
	private static Category log = Category.getInstance(UserGroupSelectTag.class);
    public static String CANDIDATE_PARAM = "candidate";
	private String contextPath = null;
	private String personId = null;
	private String domainId = null;
	private String hidden = null;
	private UserGroupHelper userGroupHelper = new UserGroupHelper();

    public UserGroupSelectTag() { }
	
    protected TreeSet<PersonPrivilegeGroupType> getGroups() {
    	TreeSet<PersonPrivilegeGroupType> groups = CoreServiceLocator.getPersonService().findPrivilegeGroupTypes();
    	return(groups);
	}

	protected String getContextPath() {
		return(contextPath);
	}
	
	public String makeStartTag() {
        log.info("makeStartTag() called");
		StringBuffer html = new StringBuffer();
		try {
			ServletRequest request = super.pageContext.getRequest();
			HttpServletRequest httpRequest = (HttpServletRequest)request;
			contextPath = httpRequest.getContextPath();
			
			log.debug("doStartTag() - finding person = " + getPersonId());
			Person person = null;		
			if (getPersonId() != null)
				person = CoreServiceLocator.getPersonService().findPersonById(new Long(getPersonId()));
	
			if (person == null) {
				log.debug("UserGroupSelectTag - Could not find person: " + getPersonId());
			}
			if ((this.hidden != null) && (this.hidden.startsWith("tr"))) {
				html.append(this.makeHiddenInputs(person, getGroups()));
			} else {
				html.append(makeGroupSection(person, getGroups()).toString());
			}
		} catch (Exception ex) {
			log.error("doStartTag() - exception ", ex);
			throw new SystemException("doStartTag() - exception ", ex);
		}
		return(html.toString());
    }

	private String makeHiddenInputs(Person person, Collection roles) {
		Person authPerson = ThreadProperties.getPerson();
		StringBuffer html = new StringBuffer();
		Iterator iter = roles.iterator();
		while (iter.hasNext()) {
    		PersonPrivilegeGroupType roleType = (PersonPrivilegeGroupType)iter.next();
    		
			if (this.userIsAuthorizedToAssignGroup(authPerson, roleType, this.getDomain())) {
				String paramName = this.userGroupHelper.getHiddenParameterName(roleType);
				html.append("<input type=\"hidden\" name=\"");
	    		html.append(paramName);
	    		html.append("\" value=\"entered");
	    		html.append("\">");
			}
		}
		return(html.toString());
	}
	
	private boolean userIsAuthorizedToAssignGroup(Person authPerson, PersonPrivilegeGroupType groupType,
			Domain domain) {
		boolean result = false;
		if (CoreServiceLocator.getUserAuthService().hasRightToAssignGroup(authPerson, groupType, domain)) {
			result = true;
		}
		return(result);
	}

    private Table makeGroupSection(Person person, Collection roles) {
		Person authPerson = this.getAuthPerson();
    	Table table = new BorderTable();
    	table.setWidth(320);
    	Iterator iter = roles.iterator();
    	if (iter.hasNext() == false) {
    	} else {
    		Row row = table.addRow();
    		//Cell labelCell = row.addCell();
			Cell cell = row.addCell();
			
			cell.addText("stdFont", "<b>" + this.getPhrase("prompt.person.privilege.group") + "</b>");

			cell = row.addCell();
			cell.addText("subFont", "None");

			cell = row.addCell();
			cell.addText("subFont", "Domain");

			cell = row.addCell();
			cell.addText("subFont", "Domain and Children");


    		while (iter.hasNext()) {
	    		PersonPrivilegeGroupType roleType = (PersonPrivilegeGroupType)iter.next();
	    		boolean personHasRolePriv = false;
	    		boolean personHasGlobalRolePriv = false;
	    		if (person != null) {
	    			PersonPrivilegeGroup group = person.findPrivilegeGroup(roleType, this.getDomain());
	    			if (group != null) {
	    				if (group.getGlobal() == true) {
	    					personHasGlobalRolePriv = true;
	    				} else {
	    					personHasRolePriv = true;
	    				}
						if ((personHasGlobalRolePriv) && (roleType.getGlobal() == false)) {
							log.debug("Changing group selection to non-global because group type does not allow it");
	    					personHasRolePriv = true;
	    					personHasGlobalRolePriv = false;
							
						}

	    			}
	    			
	    		}
	    		log.info("Creating checkbox for role: " + roleType.getCode() 
	    				+  " Person has role: " + personHasRolePriv 
	    				+ "  person.id=" + person.getId());
	    		row = table.addRow();
				cell = row.addCell();
				cell.addElement(TextHelper.getFont("subFont", this.getPhrase(roleType.getDescriptionCode())));
				boolean userAuthorizedToChange = this.userIsAuthorizedToAssignGroup(authPerson, roleType, getDomain());
				//Cell privLabelCell = row.addCell();
				//Cell groupLabelCell = row.addCell();
				Cell noPrivCell = row.addCell();
				noPrivCell.setVAlign("middle");
	
				//groupLabelCell.setVAlign("middle");
				
				if (userAuthorizedToChange) {
					Cell privCell = row.addCell();
					Cell privGlobalCell = row.addCell();
					privCell.setVAlign("middle");
					privGlobalCell.setVAlign("middle");

					
					//privLabelCell.addElement(TextHelper.getFont("subFont", this.getPhrase("phrase.role.privileges")));
					String inputName = userGroupHelper.getSelectParameterName(roleType); 
					
					Input radioNo = new Input();
					radioNo.setType(Input.RADIO);
					radioNo.setChecked(false);
					radioNo.setName(inputName);
					radioNo.setValue("none");
					if ((personHasRolePriv == false) && (personHasGlobalRolePriv == false)) {
						radioNo.setChecked(true);
					}
					noPrivCell.addElement(radioNo);

					Input radioGroup = new Input();
					radioGroup.setType(Input.RADIO);
					radioGroup.setChecked(false);
					radioGroup.setName(inputName);
					radioGroup.setValue("domain");
					if (personHasRolePriv) {
						radioGroup.setChecked(true);
					}
					privCell.addElement(radioGroup);
					

					if (roleType.getGlobal()) {
						Input radioGlobalGroup = new Input();
						radioGlobalGroup.setType(Input.RADIO);
						radioGlobalGroup.setChecked(false);
						radioGlobalGroup.setName(inputName);
						radioGlobalGroup.setValue("global");
						if (personHasGlobalRolePriv) {
							radioGlobalGroup.setChecked(true);
						}
						privGlobalCell.addElement(radioGlobalGroup);
					} else {
						privGlobalCell.addElement("&nbsp;");
					}
					
					
				} else {
					noPrivCell.setColSpan(3);
					if (personHasRolePriv) {
						noPrivCell.addElement(TextHelper.getFont("subFontGreen", this.getPhrase("phrase.has.role.privileges")));
					} else if (personHasGlobalRolePriv) {
						noPrivCell.addElement(TextHelper.getFont("subFontGreen", this.getPhrase("phrase.has.global.role.privileges")));
					} else {
						noPrivCell.addElement(TextHelper.getFont("subFontRed", this.getPhrase("phrase.has.not.role.privileges")));
						
					}
					
				}
				
	    	}
    	}
    	return(table);
    }


	/**
	 * @return Returns the domainId.
	 */
	public String getDomainId() {
		return domainId;
	}

	/**
	 * @param domainId The domainId to set.
	 */
	public void setDomainId(String domainId) {
		this.domainId = domainId;
	}

	private Domain getDomain() {
		Domain domain = null;
		domain = CoreServiceLocator.getSystemService().findDomain(new Long(this.getDomainId()));
		return(domain);
	}
	
	/**
     * @return Returns the personId.
     */
    public String getPersonId() {
        return personId;
    }
    
    /**
     * @param personId The personId to set.
     */
    public void setPersonId(String personId) {
        this.personId = personId;
    }

	/**
	 * @return Returns the hidden.
	 */
	public String getHidden() {
		return hidden;
	}

	/**
	 * @param hidden The hidden to set.
	 */
	public void setHidden(String hidden) {
		this.hidden = hidden;
	}
    
}
